package com.wocai.jrt.orgadmin.product.action;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.common.BigDecimalUtils;
import com.vteba.utils.common.PropsUtils;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.DoubleEditor;
import com.vteba.web.editer.IntEditor;
import com.vteba.web.editer.LongEditor;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.about.model.About;
import com.wocai.jrt.orgadmin.about.service.spi.AboutService;
import com.wocai.jrt.orgadmin.employee.model.EmployeeCommission;
import com.wocai.jrt.orgadmin.employee.model.EmployeeGroup;
import com.wocai.jrt.orgadmin.employee.model.GroupMember;
import com.wocai.jrt.orgadmin.employee.model.GroupProduct;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeCommissionService;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeGroupService;
import com.wocai.jrt.orgadmin.employee.service.spi.GroupMemberService;
import com.wocai.jrt.orgadmin.employee.service.spi.GroupProductService;
import com.wocai.jrt.orgadmin.fundmanager.model.FundManager;
import com.wocai.jrt.orgadmin.fundmanager.model.FundManagerProduct;
import com.wocai.jrt.orgadmin.fundmanager.service.spi.FundManagerProductService;
import com.wocai.jrt.orgadmin.fundmanager.service.spi.FundManagerService;
import com.wocai.jrt.orgadmin.investor.model.InvestorGroup;
import com.wocai.jrt.orgadmin.investor.model.InvestorGroupProduct;
import com.wocai.jrt.orgadmin.investor.model.RiskDisclosure;
import com.wocai.jrt.orgadmin.investor.service.spi.InvestorGroupProductService;
import com.wocai.jrt.orgadmin.investor.service.spi.InvestorGroupService;
import com.wocai.jrt.orgadmin.investor.service.spi.RiskDisclosureService;
import com.wocai.jrt.orgadmin.issuers.model.Issuers;
import com.wocai.jrt.orgadmin.issuers.service.spi.IssuersService;
import com.wocai.jrt.orgadmin.message.service.spi.MessageLogService;
import com.wocai.jrt.orgadmin.product.bean.CommissionSetResBean;
import com.wocai.jrt.orgadmin.product.bean.RateSetReqBean;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.model.ProductGroup;
import com.wocai.jrt.orgadmin.product.service.spi.ProductGroupService;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.ImgType;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.NumberToCNUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;
import com.wocai.jrt.orgadmin.utils.WPS2PDFUtils;
import com.wocai.jrt.orgadmin.utils.WordFormatter;
import com.wocai.jrt.orgadmin.utils.WordUtils;

/**
 * 产品控制器
 * 
 * @author yinlei
 * @date 2015-8-7 17:26:11
 */
@Controller
@RequestMapping("/product")
public class ProductAction extends GenericAction<Product> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductAction.class);

	// 任何上传文件/图片的地方都需要验证格式,没加的补上
	private static final Pattern IMAGE = Pattern.compile("^(.*)+.(jpg|jpeg|gif|png|bmp)$");
	// private static final Pattern FILE =
	// Pattern.compile("^(.*)+.(doc|pdf|txt|docx|xlsx|xls)$");

	@Inject
	private ProductService productServiceImpl;

	@Inject
	private EmployeeCommissionService employeeCommissionServiceImpl;

	@Inject
	private GroupMemberService groupMemberServiceImpl;

	@Inject
	private MessageLogService messageLogServiceImpl;

	@Inject
	private AboutService aboutServiceImpl;

	@Inject
	private FundManagerService fundManagerServiceImpl;

	@Inject
	private FundManagerProductService fundManagerProductServiceImpl;

	@Inject
	private InvestorGroupService investorGroupServiceImpl;

	@Inject
	private InvestorGroupProductService investorGroupProductServiceImpl;

	@Inject
	private EmployeeGroupService employeeGroupServiceImpl;

	@Inject
	private GroupProductService groupProductServiceImpl;

	@Inject
	private ProductGroupService productGroupServiceImpl;

	@Inject
	private RiskDisclosureService riskDisclosureServiceImpl;

	@Inject
	private IssuersService issuersServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(int.class, new IntEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 获取产品列表页面，仅仅只是页面而已
	 * 
	 * @param model
	 *            参数
	 * @return 产品List
	 */
	@RequestMapping("/list")
	public String list(Product model, Map<String, Object> maps) {
		try {
			ProductGroup productGroupParam = new ProductGroup();
			productGroupParam.setOrgId(UserUtils.getUser().getOrgId());
			List<ProductGroup> productGroupList = productGroupServiceImpl
					.pagedList(productGroupParam);
			maps.put("productGroupList", productGroupList);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
		}

		return "product/list";
	}

	/**
	 * 产品页面发起的产品查询请求，返回的是列表
	 * 
	 * @param model
	 *            参数
	 * @return 意见反馈List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody Product model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request product query, param = [{}]", JSON.toJSONString(model));

			String orgId = UserUtils.getUser().getOrgId();
			model.setOrgId(orgId);

			if (null != model.getCreateEndTime()) {
				model.setCreateEndTime(new DateTime(model.getCreateEndTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}

			int size = productServiceImpl.countBy(model);
			if (model.getPageSize() == -1) {
				model.setStart(null);
			}

			List<Product> list = new ArrayList<Product>();

			if (size > 0) {
				list = productServiceImpl.pagedList(model);
				LOGGER.info("query product list success, size = [{}]", list.size());

			}

			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request product query error, msg = [{}]", e.getMessage());
		}

		return map;
	}

	/**
	 * 根据Id获得产品实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 产品实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public Product get(String id) {
		Product model = productServiceImpl.get(id);
		return model;
	}

	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			Product product = productServiceImpl.get(id);

			Double multiply = 100.0d;
			Double subFee = product.getSubFee();
			if (null != subFee) {
				product.setSubFee(BigDecimalUtils.multiply(subFee, multiply));
			}

			Double redeemFee = product.getRedeemFee();
			if (null != redeemFee) {
				product.setRedeemFee(BigDecimalUtils.multiply(redeemFee, multiply));
			}

			Double manageFee = product.getManageFee();
			if (null != manageFee) {
				product.setManageFee(BigDecimalUtils.multiply(manageFee, multiply));
			}

			Double defaultDividend = product.getDefaultDividend();
			if (null != defaultDividend) {
				product.setDefaultDividend(BigDecimalUtils.multiply(defaultDividend, multiply));
			}

			Double defaultCommission = product.getDefaultCommission();
			if (null != defaultCommission) {
				product.setDefaultCommission(BigDecimalUtils.multiply(defaultCommission, multiply));
			}

			Double trusteeFee = product.getTrusteeFee();
			if (null != trusteeFee) {
				product.setTrusteeFee(BigDecimalUtils.multiply(trusteeFee, multiply));
			}

			// 将model放入视图中，供页面视图使用
			maps.put("product", product);

			String orgId = UserUtils.getUser().getOrgId();
			FundManager fundManager = new FundManager();
			fundManager.setOrgId(orgId);
			fundManager.setProductId(id);
			List<FundManager> fundManagerList = fundManagerServiceImpl
					.getSelectedFundManager(fundManager);
			maps.put("fundManagerList", fundManagerList);

			InvestorGroup investorGroup = new InvestorGroup();
			investorGroup.setOrgId(orgId);
			investorGroup.setProductId(id);
			List<InvestorGroup> investorGroupList = investorGroupServiceImpl
					.getSelectedInvestorGroup(investorGroup);

			InvestorGroupProduct igpParam = new InvestorGroupProduct();
			igpParam.setProductId(id);
			igpParam.setInvestorGroupId("-1");
			int igpCount = investorGroupProductServiceImpl.countBy(igpParam);

			if (null == investorGroupList) {
				investorGroupList = new ArrayList<InvestorGroup>();
			}

			if (igpCount > 0) {
				InvestorGroup ig = new InvestorGroup();
				ig.setId("-1");
				ig.setName("全部");
				ig.setSelected(true);
				ig.setProductId(id);
				investorGroupList.add(0, ig);
			} else {
				InvestorGroup ig = new InvestorGroup();
				ig.setId("-1");
				ig.setName("全部");
				ig.setSelected(false);
				ig.setProductId(id);
				investorGroupList.add(0, ig);
			}

			maps.put("investorGroupList", investorGroupList);

			// 员工组别options
			EmployeeGroup employeeGroup = new EmployeeGroup();
			employeeGroup.setOrgId(orgId);
			employeeGroup.setProductId(id);
			List<EmployeeGroup> employeeGroupList = employeeGroupServiceImpl
					.getSelectedEmployeeGroup(employeeGroup);
			maps.put("employeeGroupList", employeeGroupList);

			// 产品组别options
			ProductGroup productGroupParam = new ProductGroup();
			productGroupParam.setOrgId(orgId);
			List<ProductGroup> productGroupList = productGroupServiceImpl
					.pagedList(productGroupParam);
			maps.put("productGroupList", productGroupList);

			// 风险揭示书options
			RiskDisclosure riskDisclosureParam = new RiskDisclosure();
			riskDisclosureParam.setOrgId(orgId);
			List<RiskDisclosure> riskDisclosureList = riskDisclosureServiceImpl
					.pagedList(riskDisclosureParam);
			maps.put("riskDisclosureList", riskDisclosureList);

			// 发行方options
			Issuers issuersParam = new Issuers();
			issuersParam.setOrgId(orgId);
			List<Issuers> issuersList = issuersServiceImpl.pagedList(issuersParam);
			maps.put("issuersList", issuersList);
		} catch (Exception e) {
			LOGGER.error("get detail error, errorMsg=[{}].", e.getMessage());
		}
		return "product/edit";
	}

	/**
	 * 跳转到新增页面
	 * 
	 * @return 新增页面逻辑视图
	 */
	@RequestMapping("/add")
	public String add(Map<String, Object> maps) {
		try {
			String orgId = UserUtils.getUser().getOrgId();
			FundManager fundManager = new FundManager();
			fundManager.setOrgId(orgId);
			// fundManager.setProductId(id);
			List<FundManager> fundManagerList = fundManagerServiceImpl.pagedList(fundManager);
			maps.put("fundManagerList", fundManagerList);

			InvestorGroup investorGroup = new InvestorGroup();
			investorGroup.setOrgId(orgId);
			// investorGroup.setProductId(id);
			List<InvestorGroup> investorGroupList = investorGroupServiceImpl
					.pagedList(investorGroup);
			maps.put("investorGroupList", investorGroupList);

			EmployeeGroup employeeGroup = new EmployeeGroup();
			employeeGroup.setOrgId(orgId);
			employeeGroup.setProductId("");
			List<EmployeeGroup> employeeGroupList = employeeGroupServiceImpl
					.getSelectedEmployeeGroup(employeeGroup);
			maps.put("employeeGroupList", employeeGroupList);

			ProductGroup productGroupParam = new ProductGroup();
			productGroupParam.setOrgId(orgId);
			List<ProductGroup> productGroupList = productGroupServiceImpl
					.pagedList(productGroupParam);
			maps.put("productGroupList", productGroupList);

			// 风险揭示书options
			RiskDisclosure riskDisclosureParam = new RiskDisclosure();
			riskDisclosureParam.setOrgId(orgId);
			List<RiskDisclosure> riskDisclosureList = riskDisclosureServiceImpl
					.pagedList(riskDisclosureParam);
			maps.put("riskDisclosureList", riskDisclosureList);

			// 发行方options
			Issuers issuersParam = new Issuers();
			issuersParam.setOrgId(orgId);
			List<Issuers> issuersList = issuersServiceImpl.pagedList(issuersParam);
			maps.put("issuersList", issuersList);
		} catch (Exception e) {
			LOGGER.error("get add page error, msg=[{}]", e.getMessage());
		}
		return "product/add";
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(@Valid Product model, BindingResult errors) {
		JsonBean jsonBean = new JsonBean();
		try {

			// 对入参对象绑定参数验证
			if (errors.hasErrors()) {
				jsonBean.setCode(0);
				jsonBean.setMessage("parameter valid failure！");
				LOGGER.error("parameter valid failure, id = [{}]", model.getId());
				return jsonBean;
			}

			// 当运作方式为开放式的时候，开放日必填
			if ("0".equals(model.getOperationMode()) && StringUtils.isBlank(model.getOpenDate())) {
				jsonBean.setCode(9);
				jsonBean.setMessage("openDate is required when oprationMode is open mode！");
				LOGGER.error("openDate is required when oprationMode is open mode");
				return jsonBean;
			}

			// 查询已存在的产品详情数据，用作匹配
			Product oldModel = null;
			String productId = model.getId();
			if (!StringUtils.isBlank(productId)) {
				oldModel = productServiceImpl.get(productId);

			}

			// 验证scale的正确性
			jsonBean = validScale(model, oldModel);
			if (jsonBean.getCode() != 1) {
				LOGGER.error("validScale failure");
				return jsonBean;
			}

			// 对百分号转数字进行处理
			percent2Num(model);
			LOGGER.info("format product percent to number");

			int result = 0;
			Product oldProduct = productServiceImpl.get(productId);
			if (null == model.getShowApp()) {
				model.setShowApp(false);
			}

			if (StringUtils.isBlank(productId)) {
				model.setId(ObjectId.get().toString());
				model.setCreateTime(new Date());
				String orgId = UserUtils.getUser().getOrgId();
				model.setOrgId(orgId);
				result = productServiceImpl.save(model);

				// 所在组别加1
				String newProductGroupId = model.getProductGroupId();
				this.updateNewProductGroup(newProductGroupId);
			} else {
				// 开放日
				if (StringUtils.isBlank(model.getOpenDate())) {
					model.setOpenDate("");
				}

				// 开放周期
				if (StringUtils.isBlank(model.getOpenCycle())) {
					model.setOpenCycle("");
				}

				// 赎回费
				if (null == model.getRedeemFee()) {
					model.setRedeemFee(new Double(0));
				}

				// 管理费
				if (null == model.getManageFee()) {
					model.setManageFee(new Double(0));
				}

				// 收益分配
				if (StringUtils.isBlank(model.getIncomeDivide())) {
					model.setIncomeDivide("");
				}

				// 备注
				if (StringUtils.isBlank(model.getRemark())) {
					model.setRemark("");
				}

				// 关于页面
				if (StringUtils.isBlank(model.getAboutId())) {
					model.setAboutId("");
				}
				result = productServiceImpl.updateAddOrEditById(model);

				String newProductGroupId = model.getProductGroupId();
				String oldProductGroupId = oldModel.getProductGroupId();

				// 为空和非空，排列组合：4种情况，再用归纳法提出共同方法
				if (StringUtils.isBlank(newProductGroupId)) {
					if (StringUtils.isBlank(oldProductGroupId)) {
						LOGGER.info("not need to update any product group");
					} else {
						this.updateOldProductGroup(oldProductGroupId);
					}
				} else {
					if (StringUtils.isBlank(oldProductGroupId)) {
						this.updateNewProductGroup(newProductGroupId);
					} else {
						if (newProductGroupId.equals(oldProductGroupId)) {
							LOGGER.info(
									"not need to update any product group, newProductGroupId=[{}]",
									newProductGroupId);
						} else {
							this.updateNewProductGroup(newProductGroupId);
							this.updateOldProductGroup(oldProductGroupId);
						}
					}
				}

			}

			if (result == 1) {
				String selectedFundManager = model.getSelectedFundManager();
				if (!StringUtils.isBlank(selectedFundManager)) {
					FundManagerProduct fp = new FundManagerProduct();
					fp.setProductId(model.getId());
					fundManagerProductServiceImpl.deleteBulks(fp);
					String[] selectedFundManagers = selectedFundManager.replace("'", "")
							.replace("null", "").split(",");
					for (String s : selectedFundManagers) {
						if (!StringUtils.isBlank(s)) {
							FundManagerProduct fundManagerProduct = new FundManagerProduct();
							fundManagerProduct.setId(ObjectId.get().toString());
							fundManagerProduct.setFundManagerId(s);
							fundManagerProduct.setProductId(model.getId());
							fundManagerProductServiceImpl.save(fundManagerProduct);
						}
					}
				}

				String selectedInvestorGroup = model.getSelectedInvestorGroup();
				if (!StringUtils.isBlank(selectedInvestorGroup)) {
					InvestorGroupProduct igp = new InvestorGroupProduct();
					igp.setProductId(model.getId());
					investorGroupProductServiceImpl.deleteBulks(igp);
					String[] selectedInvestorGroups = selectedInvestorGroup.replace("'", "")
							.replace("null", "").split(",");
					for (String s : selectedInvestorGroups) {
						if (!StringUtils.isBlank(s)) {
							InvestorGroupProduct investorGroupProduct = new InvestorGroupProduct();
							investorGroupProduct.setId(ObjectId.get().toString());
							investorGroupProduct.setInvestorGroupId(s);
							investorGroupProduct.setProductId(model.getId());
							investorGroupProductServiceImpl.save(investorGroupProduct);
						}
					}
				}

				String selectedEmployeeGroup = model.getSelectedEmployeeGroup();
				if (!StringUtils.isBlank(selectedEmployeeGroup)) {
					GroupProduct gp = new GroupProduct();
					gp.setProductId(model.getId());
					groupProductServiceImpl.deleteBulks(gp);
					String[] selectedEmployeeGroups = selectedEmployeeGroup.replace("'", "").split(
							",");

					for (String s : selectedEmployeeGroups) {
						if (!StringUtils.isBlank(s)) {
							GroupProduct groupProduct = new GroupProduct();
							groupProduct.setId(ObjectId.get().toString());
							groupProduct.setGroupId(s);
							groupProduct.setProductId(model.getId());
							groupProduct.setOrgId(model.getOrgId());
							groupProduct.setBriefName(model.getBriefName());
							groupProduct.setProductCode(model.getProductCode());
							groupProduct.setType(model.getType());
							groupProduct.setCreateTime(new Date());
							groupProductServiceImpl.save(groupProduct);
						}
					}
				}

				jsonBean.setCode(1);
				jsonBean.setData(model);
				jsonBean.setMessage(SUCCESS); // 成功
				LOGGER.info("save product success.");
				// 产品状态由即将上线变成募集中状态,提醒已预约该产品的投后APP用户
				if (oldProduct != null && oldProduct.getState() == 0 && model.getState() != null
						&& model.getState() == 1) {
					// 向已预约该产品的投后APP用户推送消息
					try {
						messageLogServiceImpl.productStateChangeMessage(model);
					} catch (Exception e) {
						LOGGER.error(
								"send  jiguang push for product audit Message error, error=[{}]",
								e.getMessage());
					}
				}
			} else {
				jsonBean.setCode(0);
				jsonBean.setMessage("Fail to save product");
				LOGGER.error("save product error.");
			}

			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("save product error");
			LOGGER.error("save product error, msg = [{}]", e.getMessage());
		}

		return jsonBean;
	}

	private void updateOldProductGroup(String oldProductGroupId) {
		if (StringUtils.isNotBlank(oldProductGroupId)) {
			ProductGroup pg = productGroupServiceImpl.get(oldProductGroupId);
			if (null != pg) {
				ProductGroup productGroupParam = new ProductGroup();
				productGroupParam.setId(oldProductGroupId);

				Integer number = pg.getNumber() == null ? 0 : pg.getNumber();
				int newNumber = number - 1;
				productGroupParam.setNumber(newNumber < 0 ? 0 : newNumber);
				productGroupServiceImpl.updateById(productGroupParam);
			}
		}
	}

	private void updateNewProductGroup(String newProductGroupId) {
		if (StringUtils.isNotBlank(newProductGroupId)) {
			ProductGroup pg = productGroupServiceImpl.get(newProductGroupId);
			if (null != pg) {
				ProductGroup productGroupParam = new ProductGroup();
				productGroupParam.setId(newProductGroupId);

				Integer number = pg.getNumber() == null ? 0 : pg.getNumber();
				productGroupParam.setNumber(number + 1);
				productGroupServiceImpl.updateById(productGroupParam);
			}
		}
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/upload")
	public JsonBean upload(Product model) {
		JsonBean jsonBean = new JsonBean();
		try {
			MultipartFile productContactFile = model.getProductContactFile();
			MultipartFile productImage = model.getProductImage();

			String productId = model.getId();
			// 对入参对象绑定参数验证
			if (StringUtils.isBlank(productId)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("productId is required！");
				LOGGER.error("productId is required, productId = [{}]", productId);
				return jsonBean;
			}

			// 验证file
			jsonBean = validFile(productId, productContactFile, productImage);

			if (jsonBean.getCode() != 1) {
				jsonBean.setCode(0);
				jsonBean.setMessage("Fail to upload image/file");
				LOGGER.error("Fail to upload image/file");

				return jsonBean;
			}

			jsonBean.setMessage(SUCCESS); // 成功
			LOGGER.info("Upload image/file success.");

			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("save product error");
			LOGGER.error("save product error, msg = [{}]", e.getMessage());
		}

		return jsonBean;
	}

	private JsonBean validFile(String productId, MultipartFile productContactFile,
			MultipartFile productImage) throws IOException {
		JsonBean jsonBean = new JsonBean();
		Product oldModel = productServiceImpl.get(productId);
		Product newModel = new Product();
		newModel.setId(productId);

		if (null != productImage) {
			if (!StringUtils.isBlank(oldModel.getThumbnail())) {
				File oldImageFile = new File(oldModel.getThumbnail());
				File oldImageParent = oldImageFile.getParentFile();
				if (oldImageFile.exists()) {
					oldImageFile.delete();
					oldImageParent.delete();
				}
			}
			String productImageFilePath = MyFileUtils.uploadImg(productImage, ImgType.PRODUCT);
			newModel.setThumbnail(productImageFilePath);
		}

		if (null != productContactFile) {
			if (!StringUtils.isBlank(oldModel.getContactFile())) {
				File oldContactFile = new File(oldModel.getContactFile());
				File oldContactParent = oldContactFile.getParentFile();
				if (oldContactFile.exists()) {
					oldContactFile.delete();
					oldContactParent.delete();
				}
			}

			String productContactFilePath = MyFileUtils.uploadFile(productContactFile,
					MyFileUtils.FILE_TYPE);

			newModel.setContactFile(productContactFilePath);
		}

		if (null != productImage || null != productContactFile) {
			productServiceImpl.updateById(newModel);
		}

		jsonBean.setCode(1);
		jsonBean.setData(newModel);
		return jsonBean;
	}

	private JsonBean validScale(Product model, Product oldModel) {
		JsonBean jsonBean = new JsonBean();
		String productId = model.getId();
		Double scale = model.getScale();

		// 先算出已认购金额，再把最新的scale-已认购就等于可用
		// 新的规模不能小于已经认购的(已认购的等于旧的规模减去旧的可用余额)
		if (!StringUtils.isBlank(productId)) {
			Double oldScale = oldModel.getScale();
			Double oldAvailable = oldModel.getAvailable();

			if (null == oldAvailable) {
				model.setAvailable(scale);
			} else {
				// 已认购的金额
				Double oldBuyingAmount = BigDecimalUtils.subtract(oldScale, oldAvailable);
				if (scale < oldBuyingAmount) {
					jsonBean.setCode(0);
					jsonBean.setMessage("scale need greater than already order mount！");
					return jsonBean;
				}

				// 新的规模减去已认购的就是最新可用的
				model.setAvailable(BigDecimalUtils.subtract(scale, oldBuyingAmount));
			}
		} else {
			model.setAvailable(scale);
		}

		jsonBean.setCode(1);
		return jsonBean;
	}

	private void percent2Num(Product model) {
		Double multiply = 100.0d;
		Double subFee = model.getSubFee();
		if (null != subFee) {
			model.setSubFee(BigDecimalUtils.divide(subFee, multiply));
		}

		Double redeemFee = model.getRedeemFee();
		if (null != redeemFee && redeemFee >= 0) {
			model.setRedeemFee(BigDecimalUtils.divide(redeemFee, multiply));
		}

		Double manageFee = model.getManageFee();
		if (null != manageFee && manageFee >= 0) {
			model.setManageFee(BigDecimalUtils.divide(manageFee, multiply));
		}

		Double defaultDividend = model.getDefaultDividend();
		if (null != defaultDividend && defaultDividend >= 0) {
			model.setDefaultDividend(BigDecimalUtils.divide(defaultDividend, multiply));
		}

		Double defaultCommission = model.getDefaultCommission();
		if (null != defaultCommission && defaultCommission >= 0) {
			model.setDefaultCommission(BigDecimalUtils.divide(defaultCommission, multiply));
		}

		Double trusteeFee = model.getTrusteeFee();
		if (null != trusteeFee && trusteeFee >= 0) {
			model.setTrusteeFee(BigDecimalUtils.divide(trusteeFee, multiply));
		}
	}

	/**
	 * 查看产品详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 产品详情页
	 */
	@RequestMapping("/detail/{id}")
	public String detail(@PathVariable("id") String id, Map<String, Object> maps) {
		Product product = productServiceImpl.get(id);
		if (!StringUtils.isBlank(product.getAboutId())) {
			About about = aboutServiceImpl.get(product.getAboutId());
			if (null != about) {
				product.setAboutId(about.getTitle());
			}
		}

		// 获取基金经理
		FundManager fundManager = new FundManager();
		fundManager.setProductId(id);
		fundManager.setOrgId(UserUtils.getUser().getOrgId());
		List<FundManager> fundManagerList = fundManagerServiceImpl
				.getSelectedFundManager(fundManager);
		if (null != fundManagerList && fundManagerList.size() > 0) {
			String selectedFundManager = "";
			for (FundManager fm : fundManagerList) {
				if (fm.getSelected()) {
					selectedFundManager += "，" + fm.getName();
				}
			}

			product.setSelectedFundManager(selectedFundManager.replaceFirst("，", ""));
		}

		// 获取推送组别，有问题 -1 显示什么
		InvestorGroup investorGroup = new InvestorGroup();
		investorGroup.setProductId(id);
		investorGroup.setOrgId(UserUtils.getUser().getOrgId());
		List<InvestorGroup> investorGroupList = investorGroupServiceImpl
				.getSelectedInvestorGroup(investorGroup);
		if (null != investorGroupList && investorGroupList.size() > 0) {
			String selectedInvestorGroup = "";
			for (InvestorGroup ig : investorGroupList) {
				if (ig.getSelected()) {
					selectedInvestorGroup += "，" + ig.getName();
				}
			}

			product.setSelectedInvestorGroup(selectedInvestorGroup.replaceFirst("，", ""));
		}

		// 获取产品售卖部门
		EmployeeGroup employeeGroup = new EmployeeGroup();
		employeeGroup.setProductId(id);
		employeeGroup.setOrgId(UserUtils.getUser().getOrgId());
		List<EmployeeGroup> employeeGroupList = employeeGroupServiceImpl
				.getSelectedEmployeeGroup(employeeGroup);
		if (null != employeeGroupList && employeeGroupList.size() > 0) {
			String selectedEmployeeGroup = "";
			for (EmployeeGroup eg : employeeGroupList) {
				if (eg.getSelected()) {
					selectedEmployeeGroup += "，" + eg.getGroupName();
				}
			}

			product.setSelectedEmployeeGroup(selectedEmployeeGroup.replaceFirst("，", ""));
		}

		if (StringUtils.isNotBlank(product.getRiskDisclosureId())) {
			RiskDisclosure riskDisclosure = riskDisclosureServiceImpl.get(product
					.getRiskDisclosureId());
			if (null != riskDisclosure) {
				product.setRiskDisclosure(riskDisclosure.getName());
			}
		}

		if (StringUtils.isNotBlank(product.getIssuerId())) {
			Issuers issuer = issuersServiceImpl.get(product.getIssuerId());
			if (null != issuer) {
				product.setIssuer(issuer.getName());
			}
		}
		maps.put("product", product);// 将model放入视图中，供页面视图使用
		maps.put("relatedProductList", relatedProductList(id));

		String productGroupId = product.getProductGroupId();
		if (StringUtils.isNotBlank(productGroupId)) {
			String productGroupName = productGroupServiceImpl.get(productGroupId).getName();
			maps.put("productGroupName", productGroupName);
		}

		return "product/detail";
	}

	public List<Product> relatedProductList(String productId) {
		try {
			Product productParam = new Product();
			productParam.setOrgId(UserUtils.getUser().getOrgId());
			productParam.setId(productId);

			return productServiceImpl.relatedPagedList(productParam);
		} catch (Exception e) {
			LOGGER.error("fetch related list error, msg = [{}]", e.getMessage());
		}

		return null;
	}

	/**
	 * 更新产品信息
	 * 
	 * @param model
	 *            要更新的产品信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(Product model) {
		Double multiply = 100.0d;

		Double defaultDividend = model.getDefaultDividend();
		if (null != defaultDividend && defaultDividend >= 0) {
			model.setDefaultDividend(BigDecimalUtils.divide(defaultDividend, multiply));
		}

		Double defaultCommission = model.getDefaultCommission();
		if (null != defaultCommission && defaultCommission >= 0) {
			model.setDefaultCommission(BigDecimalUtils.divide(defaultCommission, multiply));
		}

		int result = productServiceImpl.updateById(model);
		JsonBean bean = new JsonBean();
		if (result == 1) {
			bean.setMessage(SUCCESS);
		} else {
			bean.setCode(1);
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 删除产品信息
	 * 
	 * @param id
	 *            要删除的产品ID
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(String id) {
		int result = productServiceImpl.deleteById(id);
		JsonBean bean = new JsonBean();
		if (result == 1) {
			bean.setMessage(SUCCESS);
		} else {
			bean.setCode(1);
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/***
	 * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
	 * 
	 * @param file
	 * @param flag
	 *            1 - 正面，0 - 反面
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/uploadProductImage")
	public String uploadProductImage(@RequestParam("file") MultipartFile file, String productId) {

		try {
			String fileName = file.getOriginalFilename();

			// 发起请求的参数
			LOGGER.info("request file upload, filename=[{}]", fileName);

			if (!IMAGE.matcher(fileName).matches()) {
				LOGGER.info("request image type mot mach the required");
				return null;
			}

			// 上传身份证
			String filePath = MyFileUtils.uploadImg(file, ImgType.PRODUCT);
			LOGGER.info("upload file success, filePath=[{}]", filePath);

			if (!StringUtils.isBlank(productId)) {
				Product product = new Product();
				product.setId(productId);
				product.setThumbnail(filePath);
				productServiceImpl.updateById(product);
			}

			return filePath;

		} catch (Exception e) {
			LOGGER.error("upload file error, error=[{}]", e.getMessage());
			return null;
		}

	}

	/***
	 * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
	 * 
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/downloadFile")
	public JsonBean downloadFile(String filePath, HttpServletResponse response) {
		JsonBean jsonBean = new JsonBean();
		try {
			// 发起请求的参数
			LOGGER.info("request file download, url=[{}]", filePath);

			MyFileUtils.downloadFile(filePath, response);

			// 封装jsonBean
			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS);

		} catch (Exception e) {
			LOGGER.error("download file error, error=[{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("download file error");
		}

		return jsonBean;
	}

	/**
	 * 查看产品详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 产品详情页
	 */
	@RequestMapping("/commission/{id}")
	public String commission(@PathVariable("id") String id, Map<String, Object> maps) {
		Product product = productServiceImpl.get(id);
		maps.put("product", product);// 将model放入视图中，供页面视图使用

		getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		return "product/commission";
	}

	/**
	 * 获得意见反馈List，Json格式。
	 * 
	 * @param model
	 *            参数
	 * @return 意见反馈List
	 */
	@ResponseBody
	@RequestMapping("/commissionList")
	public Map<String, Object> commissionList(@RequestBody Product model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request commissionList, param = [{}]", JSON.toJSONString(model));

			List<CommissionSetResBean> list = new ArrayList<CommissionSetResBean>();

			list.addAll(productServiceImpl.getCommissionSet(model));

			List<CommissionSetResBean> orderList = new ArrayList<CommissionSetResBean>();
			// 两种情况：1.无组别；2.无团队长
			for (int i = 0; i < list.size(); i++) {
				CommissionSetResBean iBean = list.get(i);

				// 判断是否有团队长
				if (null != iBean.getGroupName()) {
					orderList.add(iBean);
					for (int j = 0; j < list.size(); j++) {
						CommissionSetResBean jBean = list.get(j);
						if (jBean.getGroupId().equals(iBean.getGroupId())
								&& !jBean.getEmployeeId().equals(iBean.getEmployeeId())) {
							orderList.add(jBean);
						}
					}
				}

			}

			if (orderList.size() != 0) {
				for (CommissionSetResBean l : list) {
					boolean flag = false;
					for (CommissionSetResBean ol : orderList) {
						if (l.getEmployeeId().equals(ol.getEmployeeId())) {
							flag = true;
							break;
						}
					}

					if (!flag) {
						orderList.add(l);
					}
				}
			} else {
				orderList = list;
			}

			EmployeeGroup employeeGroupParam = new EmployeeGroup();
			employeeGroupParam.setProductId(model.getId());
			List<EmployeeGroup> noTeamLeaderGroup = employeeGroupServiceImpl
					.getNoTeamLeaderGroup(employeeGroupParam);

			List<String> noTeamLeaderGroupIds = new ArrayList<String>();
			if (null != noTeamLeaderGroup) {
				for (EmployeeGroup eg : noTeamLeaderGroup) {
					noTeamLeaderGroupIds.add(eg.getId());
				}
			}

			Map<Integer, CommissionSetResBean> map2 = new HashMap<Integer, CommissionSetResBean>();
			String temp = "";
			for (int i = 0; i < orderList.size(); i++) {
				CommissionSetResBean cs = orderList.get(i);
				if (!temp.equals(cs.getGroupId()) && noTeamLeaderGroupIds.contains(cs.getGroupId())) {
					CommissionSetResBean csBean = new CommissionSetResBean();
					csBean.setGroupId(cs.getGroupId());
					int index = noTeamLeaderGroupIds.indexOf(cs.getGroupId());

					csBean.setGroupName(noTeamLeaderGroup.get(index).getGroupName());
					csBean.setEmployeeName("未设置");
					map2.put(map2.size() + i, csBean);

					temp = cs.getGroupId();
				}
			}

			for (Entry<Integer, CommissionSetResBean> entry : map2.entrySet()) {
				orderList.add(entry.getKey(), entry.getValue());
			}

			map.put("aaData", orderList); // 返回的数据
			map.put("iTotalRecords", orderList.size()); // 总记录数
			map.put("iTotalDisplayRecords", orderList.size()); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request commissionList, msg = [{}]", e.getMessage());
		}

		return map;
	}

	/***
	 * 自定义设置费率
	 * 
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/setRate")
	public JsonBean setRate(RateSetReqBean rateSetReqBean) {
		JsonBean jsonBean = new JsonBean();
		try {

			// 打印请求的参数
			LOGGER.info("request set product commission/devidend rate, param = [{}]",
					JSON.toJSONString(rateSetReqBean));

			String productId = rateSetReqBean.getProductId();
			String employeeId = rateSetReqBean.getEmployeeId();
			Double dividendRate = rateSetReqBean.getDividendRate();
			Double commissionRate = rateSetReqBean.getCommissionRate();
			if (null == dividendRate && null == commissionRate) {
				jsonBean.setCode(0);
				jsonBean.setMessage("dividendRate and commissionRate have at least one non null");
				LOGGER.info("dividendRate and commissionRate have at least one non null");
				return jsonBean;
			}

			EmployeeCommission ecParam = new EmployeeCommission();
			ecParam.setProductId(productId);
			ecParam.setEmployeeId(employeeId);
			EmployeeCommission employeeCommission = employeeCommissionServiceImpl.unique(ecParam);
			EmployeeCommission ecData = new EmployeeCommission();
			GroupMember gmParam = new GroupMember();
			gmParam.setEmployeeId(employeeId);
			GroupMember groupMember = groupMemberServiceImpl.unique(gmParam);
			if (null == employeeCommission) {
				ecData.setId(ObjectId.get().toString());
				ecData.setProductId(productId);
				ecData.setEmployeeId(employeeId);
				ecData.setCreateTime(new Date());
				ecData.setGroupId(null != groupMember ? groupMember.getGroupId() : null);
				ecData.setOrgId(UserUtils.getUser().getOrgId());
			}

			if (null != dividendRate) {
				LOGGER.info("request setRate, dividendRate=[{}]", dividendRate);
				ecData.setDividendRate(BigDecimalUtils.divide(dividendRate, 100.00));
			}

			if (null != commissionRate) {
				LOGGER.info("request setRate, commissionRate=[{}]", commissionRate);
				ecData.setCommissionRate(BigDecimalUtils.divide(commissionRate, 100.00));
			}

			int count = 0;
			if (null == employeeCommission) {
				count = employeeCommissionServiceImpl.save(ecData);
			} else {
				EmployeeCommission ecCondition = new EmployeeCommission();
				ecCondition.setProductId(productId);
				ecCondition.setEmployeeId(employeeId);
				count = employeeCommissionServiceImpl.updateBulks(ecData, ecCondition);
			}

			if (count == 1) {
				jsonBean.setCode(1);
				jsonBean.setMessage("set rate success");
				LOGGER.info("set rate success, rateRecord=[{}]", JSON.toJSONString(ecData));
			} else {
				jsonBean.setCode(0);
				jsonBean.setMessage("set rate fail");
				LOGGER.info("set rate fail");
			}

		} catch (Exception e) {
			LOGGER.error("set rate error, errorMsg=[{}].", e.getMessage());
			jsonBean.setMessage(ERROR);
		}
		return jsonBean;
	}

	/***
	 * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
	 * 
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/downloadEffect")
	public JsonBean downloadEffect(String productId, HttpServletResponse response) {
		JsonBean jsonBean = new JsonBean();
		try {
			String filePath = productServiceImpl.get(productId).getContactFile();

			// 发起请求的参数
			LOGGER.info("request downloadEffect, url=[{}]", filePath);

			if (StringUtils.isBlank(filePath)) {
				jsonBean.setCode(0);
				jsonBean.setMessage("downloadEffect error with filePath is blank");
				LOGGER.error("downloadEffect error with filePath is blank");

				return jsonBean;
			}

			String destPath = null;

			if (filePath.endsWith(".docx")) {
				Map<String, String> map = new HashMap<String, String>();
				WordFormatter wf = new WordFormatter();
				wf.setContractNumber("ZJT00001");// 合同编号
				wf.setInvestorName("陈康");// 投资人姓名
				wf.setInvestorSignName(PropsUtils.get("contact_template_image"));// 投资人签名，这里是图片
				wf.setSignTime("2015年10月15日");// 签单时间

				double amount = 3000000;
				DecimalFormat format = new DecimalFormat("#,##0.00");
				wf.setAmount(format.format(amount));// 投资金额
				wf.setAmountToCN(NumberToCNUtils.number2CNMontrayUnit(BigDecimal.valueOf(amount)));// 投资金额大写
				wf.setIDCard("511702197207108849");// 证件号
				wf.setAddress("浙江省杭州市西湖区 天亿大厦1609室");// 通信地址
				wf.setPhone("15158487263");// 联系电话
				wf.setEmail("1045776832@qq.com");// 邮件
				wf.setBankName("招商银行拱墅支行");// 开户行
				wf.setAccountName("陈康");// 开户名
				wf.setBankAccount("6216617611000234453");// 银行帐（卡）号
				wf.setElectronic(PropsUtils.get("electronic_template_image"));

				Field[] fields = wf.getClass().getDeclaredFields();
				for (Field field : fields) {
					field.setAccessible(true);
					String fieldValue = String.valueOf(field.get(wf));
					if (!"null".equals(fieldValue)) {
						map.put(field.getName(), fieldValue);
					} else {
						map.put(field.getName(), "");
					}

					System.out.println(field.getName() + ": " + fieldValue);
				}

				map.put("[", "");
				map.put("]", "");

				// String srcPath = "D:\\word_test\\word_test.docx";
				String filename = new File(filePath).getName();

				String docxPath = MyFileUtils.getFilePath(filename, MyFileUtils.DOC_TYPE);
				WordUtils.searchAndReplace(filePath, docxPath, map);
				LOGGER.info("replace docx success");

				destPath = MyFileUtils.getFilePath(filename.replace(".docx", "预览.pdf"),
						MyFileUtils.PDF_TYPE);
				WPS2PDFUtils.word2PDF(docxPath, destPath);
				LOGGER.info("convert docx to pdf success");
			}

			MyFileUtils.downloadFileByPath(destPath, response);

			File effectFile = new File(destPath);
			if (effectFile.exists()) {
				File parent = effectFile.getParentFile();
				effectFile.delete();
				parent.delete();
			}

			// 封装jsonBean
			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS);

		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("downloadEffect error");
			LOGGER.error("downloadEffect error, error=[{}]", e.getMessage());
		}

		return jsonBean;
	}

	/**
	 * 获取产品审核页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/listAudit")
	public String listAudit(Product model) {
		return "product/listAudit";

	}

	/**
	 * 产品页面发起的产品查询请求，返回的是列表
	 * 
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryAudit")
	public Map<String, Object> queryAudit(@RequestBody Product model) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			LOGGER.info("request product queryAudit, param = [{}]", JSON.toJSONString(model));
			String orgId = UserUtils.getUser().getOrgId();
			model.setOrgId(orgId);
			int size = productServiceImpl.countBy(model);
			if (model.getPageSize() == -1) {
				model.setStart(null);
			}
			List<Product> list = new ArrayList<Product>();
			if (size > 0) {
				model.setOrderBy("audit_state");
				list = productServiceImpl.pagedList(model);
				LOGGER.info("query product list success, size = [{}]", list.size());
			}
			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("request product query error, msg = [{}]", e.getMessage());
		}
		return map;
	}

	/**
	 * 产品审核不通过
	 * 
	 * @param model
	 *            要更新的产品信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/auditNoPass/{id}")
	public JsonBean auditNoPass(@PathVariable("id") String id) {
		Product product = new Product();
		product.setId(id);
		product.setAuditState(0);
		int result = productServiceImpl.updateById(product);
		JsonBean bean = new JsonBean();
		if (result == 1) {
			bean.setCode(1);
			bean.setMessage(SUCCESS);
		} else {
			bean.setCode(0);
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 产品审核通过
	 * 
	 * @param model
	 *            要更新的产品信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/auditPass/{id}")
	public JsonBean auditPass(@PathVariable("id") String id) {
		Product product = new Product();
		product.setId(id);
		product.setAuditState(1);
		int result = productServiceImpl.updateById(product);
		JsonBean bean = new JsonBean();
		if (result == 1) {
			bean.setCode(1);
			bean.setMessage(SUCCESS);
			// 产品审核通过,向投后APP用户推送消息
			try {
				messageLogServiceImpl.productAuditMessage(id);
			} catch (Exception e) {
				LOGGER.error("send  jiguang push for product audit Message error, error=[{}]",
						e.getMessage());
			}
		} else {
			bean.setCode(0);
			bean.setMessage(ERROR);
		}
		return bean;
	}

	@ResponseBody
	@RequestMapping("/about")
	public JsonBean about() {
		JsonBean jsonBean = new JsonBean();
		try {
			String orgId = UserUtils.getUser().getOrgId();

			About aboutParam = new About();
			aboutParam.setOrgId(orgId);
			List<About> list = aboutServiceImpl.queryList(aboutParam);
			LOGGER.info("fetch about list success.");

			jsonBean.setCode(1);
			jsonBean.setData(list);
			jsonBean.setMessage(SUCCESS); // 成功

			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("fetch about list error");
			LOGGER.error("fetch about list error, msg = [{}]", e.getMessage());
		}

		return jsonBean;
	}

	@ResponseBody
	@RequestMapping("/fundManager")
	public JsonBean fundManager() {
		JsonBean jsonBean = new JsonBean();
		try {
			String orgId = UserUtils.getUser().getOrgId();

			FundManager fundManagerParam = new FundManager();
			fundManagerParam.setOrgId(orgId);
			List<FundManager> list = fundManagerServiceImpl.queryList(fundManagerParam);
			LOGGER.info("fetch fundManager list success.");

			jsonBean.setCode(1);
			jsonBean.setData(list);
			jsonBean.setMessage(SUCCESS); // 成功

			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("fetch fundManager list error");
			LOGGER.error("fetch afundManager list error, msg = [{}]", e.getMessage());
		}

		return jsonBean;
	}

	@ResponseBody
	@RequestMapping("/check")
	public boolean check(Product model) {
		model.setOrgId(UserUtils.getOrgId());

		if (StringUtils.isBlank(model.getId())) {
			return productServiceImpl.nativeCountBy(model) > 0 ? false : true;
		} else {
			String productId = model.getId();
			model.setId(null);
			Product product = productServiceImpl.unique(model);
			return !productId.equals(product.getId()) ? false : true;
		}
	}
}
